package mylab.starters.mybatis.support.mixedSource;

import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.dynamic.datasource.support.DdConstants;
import lombok.extern.slf4j.Slf4j;
import mylab.starters.mybatis.config.DbProperties;
import mylab.starters.mybatis.config.tenant.TenantMode;
import mylab.starters.mybatis.support.mixedSource.impl.TenantDataSourceJdbcLoader;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 从主数据源中获取其它动态数据源的配置信息
 */
@Slf4j
public class TenantDataSourceProvider extends AbstractDataSourceProvider implements DynamicDataSourceProvider {

    private DynamicDataSourceProperties properties;
    //    private BasicDataSourceProperties dataSourceProperties;
    private DbProperties dbProperties;

    public TenantDataSourceProvider(DynamicDataSourceProperties properties, DbProperties dbProperties) {
        this.properties = properties;
        this.dbProperties = dbProperties;
    }

    @Override

    public Map<String, DataSource> loadDataSources() {
        Map<String, DataSourceProperty> map = new HashMap<>(8);

        //包含yml配置的数据源
        map.putAll(properties.getDatasource());

        //租户独立数据源模式
        if (dbProperties.getTenant().getMode().equals(TenantMode.DATASOURCE)) {

            TenantDataSourceLoader loader = new TenantDataSourceJdbcLoader(getMaster(), dbProperties);
            map.putAll(loader.getAll());
        }
        return createDataSourceMap(map);
    }


    private DataSourceProperty getMaster() {
        return properties.getDatasource().get(DdConstants.MASTER);
    }


}
